const mongoose = require('mongoose')
const Router = require('koa-router')
const nodeXlsx = require('node-xlsx')
const fs = require('fs')
const moment = require('moment')
const lodash = require('lodash')
// 解析markdown
const MarkdownIt = require('markdown-it')
const md = new MarkdownIt()
const ArticleSchema = mongoose.model('ArticleSchema')
const ArticleRouter = new Router()

ArticleRouter.post('/add', async (ctx)=> {
  const body = ctx.request.body
  body.userName = ctx.cookies.get('name')
  body.rawContent = body.content // 在编辑的时候使用的字段
  if (body.contentType === 'markdown') {
    body.content = md.render(body.content) // 在详情的信息中使用的字段
  }
  try {
    await new ArticleSchema(body).save()
    ctx.body = {
      code: 200,
      message: '提交成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }
})

ArticleRouter.get('/get', async (ctx) => {
  try {
    const query = ctx.request.query
    const rows = query.rows * 1
    const page = query.page * 1
    const skipCount = (query.page - 1) * query.rows
    const total = await ArticleSchema.find().countDocuments().exec()
    const list = await ArticleSchema.find().skip(skipCount).limit(rows).sort({ publishTime: -1 }).exec()
    // 判断当前用户是否可以进行编辑和删除操作
    list.forEach(ele => ele.canOperate = ele.userName === ctx.cookies.get('name'))
    ctx.body = {
      code: 200,
      message: list,
      current: page,
      pageSize: rows,
      total
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }
})

ArticleRouter.put('/edit', async ctx => {
  try {
    const { body } = ctx.request
    const obj = {
      rawContent: body.content,
      content: body.contentType === 'markdown' ? md.render(body.content) : body.content,
      contentType: body.contentType,
      publishTime: Date.now()
    }
    await ArticleSchema.findOneAndUpdate({ _id: body.id }, obj).exec()
    ctx.body = {
      code: 200,
      message: '编辑成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '编辑失败'
    }
  }
})

ArticleRouter.delete('/delete', async ctx => {
  try {
    const { id } = ctx.request.query
    await ArticleSchema.findOneAndDelete({ _id: id }).exec()
    ctx.body = {
      code: 200,
      message: '删除成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '删除失败'
    }
  }
})

ArticleRouter.get('/detail', async ctx => {
  try {
    const { id } = ctx.request.query
    const articleItem = await ArticleSchema.findById(id).exec()
    ctx.body = {
      code: 200,
      message: articleItem
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }
})

ArticleRouter.get('/export', async ctx => {
  try {
    // 0代表不查出来的字段， 1代表是查出来的字段
    const list = await ArticleSchema.find({}, { _id: 0, userName: 1, publishTime: 1, contentType: 1 }).exec()
    const valuesArr = list.map(item => [item.userName, item.contentType, moment(item.publishTime).format('YYYY-MM-DD HH:mm:ss')])
    valuesArr.unshift(['用户名', '内容类型', '发布时间'])
    const bufferData = nodeXlsx.build([{ name: '报表', data: valuesArr }])
    const lodashCount = lodash.uniqueId()
    ctx.body = {
      code: 200,
      message: lodashCount
    }
    // 命名不同的文件名，否则报错
    fs.writeFileSync(`${__dirname}/downloads/xlsx_${lodashCount}.xlsx`, bufferData)
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '导出失败',
      error
    }
  }
})



module.exports = ArticleRouter